var Global = require("../util/global.js");
var message = require("../util/message.js");

cc.Class({
    extends: cc.Component,

    properties: {
        bg:{
            type:cc.Sprite,
            default:null,
        },
        gameTimeLabel:{
            type:cc.Label,
            default:null,
        },
        gameSpeed:5,                //游戏速度
        gameTime:0,                 //游戏总时间
        updateIndex:0,
        uname:{
            type:cc.Label,
            default:null,
        },
        toUname:{
            type:cc.Label,
            default:null,
        },
        bulletPanel:{
            type:cc.Layout,
            default:null,
        },
        bullet1:{
            type:cc.Sprite,
            default:null,
        },
        bullet2:{
            type:cc.Sprite,
            default:null,
        },
        bullet3:{
            type:cc.Sprite,
            default:null,
        },
        toBullet1:{
            type:cc.Sprite,
            default:null,
        },
        toBullet2:{
            type:cc.Sprite,
            default:null,
        },
        toBullet3:{
            type:cc.Sprite,
            default:null,
        },
        optionIndexs:null,          //所有选项
        option:{                    //选项预制
            type:cc.Prefab,
            default:null,
        },

        bulletIndex:0,              //我方当前飞行炮弹下标
        toBulletIndex:0,            //敌方当前飞行炮弹下标
        
        bulletThread:null,          //我方炮弹飞行线程
        toBulletThread:null,        //敌方炮弹飞行线程

        bloodTotal:3,               //我的血量
        blood:{                     //我的血槽
            type:cc.ProgressBar,
            default:null,
        },
        toBloodTotal:3,             //敌方血量
        toBlood:{                   //敌方血槽
            type:cc.ProgressBar,
            default:null,
        },

        isBulleting:false,          //是否在发射中
        
        bulletCount:0,              //发射次数
        toBulletCount:0,            //接收次数

        isSendWin:false,            //是否发送战斗结果
    },

    // onLoad () {},

    start () {
        // cc.director.loadScene('over');
        this.init();
        this.hideBulletPanel();
    },
    /**
     * 初始化
     * @return {[type]} [description]
     */
    init(){
        this.initData();
    },
    /**
     * 初始化数据
     * @return {[type]} [description]
     */
    initData(){
        //开启碰撞引擎
        cc.director.getCollisionManager().enabled = true;

        //背景旋转
        this.bg.node.runAction(cc.repeatForever(cc.rotateBy(100,360)));

        //修改战斗界面信息
        this.uname.getComponent(cc.Label).string = Global.uname;
        this.toUname.getComponent(cc.Label).string = Global.toUname;

        //重置websocket
        Global.socket.sock.parent = this;
        Global.socket.sock.onmessage = this.onMessage;

        //重置敌方用户id
        message.toUid = Global.toUid;

        //重置子弹仓库
        Global.toBullets = [];
        this.optionIndexs = ['A','B','C','D','E','F','G'];

        //重置胜利标识
        Global.isWin = 0;
    },
    /**
     * websocket接收消息
     * @param  {[type]} result [description]
     * @return {[type]}        [description]
     */
    onMessage(result){
        cc.log("接收消息:"+result.data);

        var self = this.parent;

        var message = JSON.parse(result.data);

        if(message.type==11){
            cc.log("敌方发射炮弹");

            self.toBulletIndex = parseInt(message.content.order);
            Global.toBullets[self.toBulletIndex] = message.content;
            self.showBulletPanel(message.content);
            //敌方炮弹移动
            var toBullet = eval("self.toBullet"+(self.toBulletIndex+1));
            self.toBulletThread = setInterval(function(){
                toBullet.node.y-=0.1*self.gameSpeed;
            },10);
            //敌方发射次数+1
            self.toBulletCount++;
        }else if(message.type==12){
            cc.log("敌方答题正确");

            //本地缓存写入敌方选择
            Global.bullets[self.bulletIndex].choose = message.content;

            //移除炮弹
            clearInterval(self.bulletThread);
            var bullet = eval("self.bullet"+(self.bulletIndex+1));
            if(bullet)bullet.node.removeFromParent();

            //是否发射中置为false
            self.isBulleting = false;

            //判定是否胜利或失败
            if(self.bulletCount==3&&self.toBulletCount==3){
                if(self.bloodTotal>self.toBloodTotal){
                    self.gameWin();
                }else if(self.bloodTotal==self.toBloodTotal){
                    self.gamePeace();
                }else{
                    self.gameLose();
                }
            }

        }else if(message.type==13){
            cc.log("敌方答题错误");

            //本地缓存写入敌方选择 
            Global.bullets[self.bulletIndex].choose = message.content;

            //我方炮弹快速移动
            clearInterval(self.bulletThread);
            var bullet = eval("self.bullet"+(self.bulletIndex+1));
            self.bulletThread = setInterval(function(){
                bullet.node.y+=1*self.gameSpeed;
            },1);

            //是否发射中置为false
            self.isBulleting = false;

            //判定是否胜利或失败
            if(self.bulletCount==3&&self.toBulletCount==3){
                if(self.bloodTotal>self.toBloodTotal){
                    self.gameWin();
                }else if(self.bloodTotal==self.toBloodTotal){
                    self.gamePeace();
                }else{
                    self.gameLose();
                }
            }

        }else if(message.type==88){
            cc.log("敌方胜利");

            self.gameLose();
        }else if(message.type==89){
            cc.log("敌方失败");
            
            self.gameWin();
        }else if(message.type==90){
            cc.log("双方平局");
            
            self.gamePeace();
        }
    },
    /**
     * 我方发射炮弹
     * @param  {[type]} target [description]
     * @param  {[type]} bid    [description]
     * @return {[type]}        [description]
     */
    onBullet(target,bid){
        cc.log("我方发射炮弹:"+bid);

        if(this.isBulleting){
            cc.log("炮弹还未完成");
            return;
        }else{
            this.isBulleting = true;
        }

        var self = this;
        message.type = 11;
        message.content = Global.bullets[bid-1];
        message.content.order = bid-1;
        Global.socket.sendData(message);
        //我方炮弹移动
        this.bulletIndex = bid-1;
        var bullet = eval("self.bullet"+bid);
        this.bulletThread = setInterval(function(){
            bullet.node.y+=0.1*self.gameSpeed;
        },10);
        //我方发射次数+1
        this.bulletCount++;
    },
    /**
     * 绑定回答问题事件
     * @param  {[type]} option [description]
     * @param  {[type]} aid    [description]
     * @return {[type]}        [description]
     */
    bindClickEvent: function (option, aid) {
       var clickEventHandler = new cc.Component.EventHandler();
       //这个 node 节点是你的事件处理代码组件所属的节点
       clickEventHandler.target = this.node; 
       //这个是代码文件名
       clickEventHandler.component = "game";
       clickEventHandler.handler = "onAnswer";
       clickEventHandler.customEventData = aid;
       option.clickEvents.push(clickEventHandler);
    },
    /**
     * 回答问题
     * @param  {[type]} target [description]
     * @param  {[type]} aid    [description]
     * @return {[type]}        [description]
     */
    onAnswer(target,aid){
        cc.log("用户选择了:"+aid);

        var self = this;

        //取出正确答案
        var answer = Global.toBullets[this.toBulletIndex].answer;

        //判断用户是否答对,对了炮弹消失,并发送webscoket消息
        if(answer==aid){
            message.type = 12;
            message.content = aid;
            Global.socket.sendData(message);
            Global.toBullets[this.toBulletIndex].choose = aid;
            clearInterval(this.toBulletThread);
            var toBullet = eval("self.toBullet"+(self.toBulletIndex+1));
            toBullet.node.removeFromParent();
        //错了炮弹加速
        }else{
            message.type = 13;
            message.content = aid;
            Global.socket.sendData(message);
            Global.toBullets[this.toBulletIndex].choose = aid;
            clearInterval(this.toBulletThread);
            //敌方炮弹快速移动
            var toBullet = eval("self.toBullet"+(self.toBulletIndex+1));
            this.toBulletThread = setInterval(function(){
                toBullet.node.y-=1*self.gameSpeed;
            },1);
        }

        //存入全局变量,方便展示结果
        

        this.hideBulletPanel();
    },
    /**
     * 显示答题面板
     * @param  {[type]} bullet [description]
     * @return {[type]}        [description]
     */
    showBulletPanel(bullet){
        cc.log("显示答题面板");

        var self = this;

        this.bulletPanel.node.getChildByName('options').removeAllChildren();
        this.bulletPanel.node.active = true;
        
        //定义回调输出选项的匿名方法
        var callback = function(){
            for(var i=0;i<bullet.optionList.length;i++){
                var option = cc.instantiate(self.option);
                self.delayPrint(option.getComponent(cc.Label),self.optionIndexs[i]+'.'+bullet.optionList[i],i);
                self.bindClickEvent(option.getComponent(cc.Button),self.optionIndexs[i]);
                self.bulletPanel.node.getChildByName('options').addChild(option);
            }
        }

        this.typerPrint(this.bulletPanel.node.getChildByName('subject').getComponent(cc.Label),bullet.subject,callback);
    },
    /**
     * 打字机效果
     * @param  {[type]} label   [description]
     * @param  {[type]} content [description]
     * @return {[type]}         [description]
     */
    typerPrint(label,content,callback){
        cc.log("打字机效果");

        label.string = "";
        content = "    "+content;
        var i=4;
        var len = content.length;
        var typerThread = setInterval(function(){
            label.string = content.substring(0,++i);
            if(i==len){
                clearInterval(typerThread);
                if(callback)callback();
            }
        },100);
    },
    /**
     * 延迟输出
     * @return {[type]} [description]
     */
    delayPrint(label,content,delay){
        cc.log("延迟输出");

        label.string = "";
        setTimeout(function(){
            label.string = content;
        },delay*300);
    },
    /**
     * 隐藏答题面板
     * @return {[type]} [description]
     */
    hideBulletPanel(){
        cc.log("隐藏答题面板");

        this.bulletPanel.node.active = false;
    },
    /**
     * 游戏胜利
     * @return {[type]} [description]
     */
    gameWin(){
        clearInterval(this.bulletThread);
        clearInterval(this.toBulletThread);

        Global.isWin = 1;
        Global.victory++;


        if(!this.isSendWin){
            this.isSendWin = true;
            message.type=88;
            message.content="我方胜利";
            Global.socket.sendData(message);
        }

        cc.director.loadScene('over');
    },
    /**
     * 游戏失败
     * @return {[type]} [description]
     */
    gameLose(){
        clearInterval(this.bulletThread);
        clearInterval(this.toBulletThread);

        Global.isWin = -1;
        Global.victory = 0;

        if(!this.isSendWin){
            this.isSendWin = true;
            message.type=89;
            message.content="我方失败";
            Global.socket.sendData(message);
        }

        cc.director.loadScene('over');
    },
    /**
     * 游戏平局
     * @return {[type]} [description]
     */
    gamePeace(){
        clearInterval(this.bulletThread);
        clearInterval(this.toBulletThread);

        Global.isWin = 0;

        if(!this.isSendWin){
            this.isSendWin = true;
            message.type=90;
            message.content="双方平局";
            Global.socket.sendData(message);
        }

        cc.director.loadScene('over');
    },
    update (dt) {
        if(this.updateIndex%100==0){
            this.gameTime++;
            this.gameTimeLabel.string = "战斗持久了"+this.gameTime+"秒";
        }
        this.updateIndex++;
    },
});
